import { t } from 'i18next'
import React, { FC, createContext } from 'react'
import { Button } from '@kedacom/react-next'
import { ProvideDefault, RowRendererProps } from './translator'
import { RightWrap, ListItemGhost } from '../../components'
import { ListEmpty, ListTop, ListBody, ActionType } from '@/components/List'
import { Droppable, Draggable, DragDropContextProvider } from '@/plugins/dnd'
import { FixedSizeList as List } from 'react-window'
import { ListItem } from './ListItem'
import { Wrap, Label, Separator, StyledPollSelectItem, BtnWrap, StyledPlanModal } from './style'
import { useData } from './hooks'
import AutoSizer from 'react-virtualized-auto-sizer'
import { CheckBox, InputNumber, Modal, Select, Input } from '@kedacom/react-next'
import shallow from 'zustand/shallow'
import { usePollStore } from './store'
import { revert_mt } from '@/api/manager/mt'
import { getCheckPreNameRule } from '@/utils'
import { useGlobalStore } from '@/store/global'

const rowRenderer = React.memo(({ data: list, index, style }: RowRendererProps) => {
	const rowData = list[index]
	const dataTransfer = () => {
		return {
			data: {
				mt: revert_mt(rowData.mcc),
				poll: {},
			},
			from: 'poll',
		}
	}
	return (
		<Draggable
			style={style}
			index={index}
			dataTransfer={dataTransfer}
			ghostRender={<ListItemGhost data={rowData.mcc} />}
		>
			<ListItem {...rowData} />
		</Draggable>
	)
})
export const PollContext = createContext({} as ProvideDefault)
const Poll: FC = () => {
	const SWITCH = useGlobalStore((state) => state.SWITCH)

	const {
		inputRef,
		topActions,
		keepTimedisabled,
		disabled,
		handleDrop,
		startPoll,
		stopPoll,
		pausePoll,
		changePlan,
		deletePlan,
		handleReturnBack,
		savePlan,
		resumePoll,
		handleRemoveMt,
		addPlan,
		handleClickLi,
	} = useData()
	const {
		list,
		state,
		unlimited,
		poll_mode,
		planOptions,
		planValue,
		keep_time,
		isSavePlanOpen,
		name,
		num,
		pollIntervalOptionsVal,
		pollIntervalOptions,
		poll_mode_text,
		update,
		handleDown,
		handleDownBottom,
		handleUp,
		handleUpTop,
		mode,
	} = usePollStore(
		(state) => ({
			list: state.list,
			update: state.update,
			state: state.state,
			unlimited: state.unlimited,
			poll_mode: state.poll_mode,
			poll_mode_text: state.poll_mode_text,
			planOptions: state.planOptions,
			preName: state.preName,
			planValue: state.planValue,
			isUpload: state.is_upload,
			keep_time: state.keep_time,
			isSavePlanOpen: state.isSavePlanOpen,
			name: state.name,
			num: state.num,
			pollIntervalOptionsVal: state.pollIntervalOptionsVal,
			pollIntervalOptions: state.pollIntervalOptions,
			mode: state.mode,
			handleUp: state.handleUp,
			handleUpTop: state.handleUpTop,
			handleDown: state.handleDown,
			handleDownBottom: state.handleDownBottom,
		}),
		shallow
	)
	/**根据轮询状态获取操作按钮*/
	const optionBtn = () => {
		return (
			<BtnWrap className="poll-btns__i18n">
				{/* 空闲*/}
				{state === 0 && (
					<Button
						disabled={list.length === 0}
						onClick={startPoll}
						style={{ margin: '0 0 0 6px', width: '80px', padding: '0 10px' }}
					>
						{t('开始轮询')}
					</Button>
				)}
				{/* 轮询中*/}
				{state === 1 && (
					<Button onClick={pausePoll} style={{ margin: '0 0 0 6px', width: '80px', padding: '0 10px' }}>
						{t('暂停轮询')}
					</Button>
				)}
				{/* 暂停*/}
				{state === 2 && (
					<Button onClick={resumePoll} style={{ margin: '0 0 0 6px', width: '80px', padding: '0 10px' }}>
						{t('继续轮询')}
					</Button>
				)}
				{/* 暂停 轮询中*/}
				{(state === 1 || state === 2) && (
					<Button
						onClick={stopPoll}
						style={{ margin: '0 0 0 6px', color: '#c62619', width: '80px', padding: '0 10px' }}
					>
						{t('结束轮询')}
					</Button>
				)}
			</BtnWrap>
		)
	}
	return (
		<PollContext.Provider value={{ remove: handleRemoveMt, handleClickLi }}>
			<RightWrap title={poll_mode_text} onBack={handleReturnBack} action={optionBtn()}>
				<Wrap>
					<Label title={t('轮询预案')}>{t('轮询预案')}</Label>
					<Select
						width={115}
						options={planOptions}
						value={planValue}
						disabled={disabled}
						onClick={(e, v) => changePlan(v)}
						optionRender={(option, selected) => (
							<StyledPollSelectItem className={selected ? 'selected' : ''}>
								<span className="select-icon"></span>
								<span className="text" title={option.label}>
									{option.label}
								</span>
								{option.value !== '0' && (
									<span
										className="delete-icon"
										onClick={(e) => {
											e.stopPropagation()
											deletePlan(option as { label: string; value: string })
										}}
									>
										×
									</span>
								)}
							</StyledPollSelectItem>
						)}
					/>
					<Button onClick={savePlan} style={{ margin: '0 0 0 10px' }} className="save-poll-pre__i18n">
						{t('保存预案')}
					</Button>
				</Wrap>
				<ListTop title={t('轮询列表')} num={list.length} actions={topActions} />
				<ListBody
					order={(type) => {
						if (type === 'top') {
							handleUpTop()
						}
						if (type === 'up') {
							handleUp()
						}
						if (type === 'down') {
							handleDown()
						}
						if (type === 'bottom') {
							handleDownBottom()
						}
					}}
					disabled={list.length === 0}
					_height={180}
				>
					<AutoSizer>
						{({ height }) => (
							<DragDropContextProvider>
								<Droppable onDrop={handleDrop}>
									{(setDroppableRef) =>
										list.length > 0 ? (
											<List
												width={248}
												height={height}
												itemCount={list.length}
												itemSize={32}
												itemData={list}
												outerRef={setDroppableRef}
												itemKey={(index, data) => data[index].mtKey}
											>
												{rowRenderer}
											</List>
										) : (
											<ListEmpty width={248} height={height} outerRef={setDroppableRef} />
										)
									}
								</Droppable>
							</DragDropContextProvider>
						)}
					</AutoSizer>
				</ListBody>
				<Separator></Separator>
				<Wrap height={40}>
					<Label title={t('轮询次数')}>{t('轮询次数')}</Label>
					<InputNumber
						width={45}
						disabled={keepTimedisabled}
						value={num}
						onChange={(e, val) => {
							update({
								num: val === '' ? undefined : Number(val),
							})
						}}
						maxLength={4}
					/>
					<span className={`${unlimited ? 'disabled' : ''} msg poll-time-msg__i18n`}> {t('1~9999次')}</span>
					<CheckBox
						className="unlimited"
						checked={unlimited}
						onChange={(e, val) => {
							update({
								unlimited: val,
								num: undefined,
							})
						}}
						disabled={disabled}
						style={{ margin: '0 0 0 35px' }}
					>
						{t('不限次数')}
					</CheckBox>
				</Wrap>
				<Wrap height={40}>
					<Label className="interval-label" title={t('轮询间隔')}>
						{t('轮询间隔')}
					</Label>
					<Select
						width={65}
						className="interval-select__i18n"
						panelClassName="interval-select-panel__i18n"
						options={pollIntervalOptions}
						disabled={state === 1 || state === 2}
						value={pollIntervalOptionsVal}
						onChange={(e, v) => {
							let time = 30
							if (v === '0') {
								time = 5
							} else {
								time = Number(v)
							}
							update({
								keep_time: time,
							})
						}}
					/>
					{pollIntervalOptionsVal === '0' && (
						<>
							<InputNumber
								className="keep-time-input__i18n"
								width={45}
								value={keep_time}
								onChange={(e, v) => {
									update({
										keep_time: v === '' ? undefined : Number(v),
									})
								}}
								disabled={state === 1 || state === 2}
								style={{ margin: '0 0 0 39px' }}
								maxLength={4}
							/>
							<span className="msg">{t('5~7200秒')}</span>
						</>
					)}
				</Wrap>
				{(poll_mode === 1 || poll_mode === 2) && (
					<Wrap>
						<CheckBox
							className="name-setting"
							checked={mode === 1 ? false : true}
							onChange={(e, val) => {
								update({ mode: val ? 3 : 1 })
							}}
							disabled={disabled}
						>
							{poll_mode === 1 && t('轮询到的终端成为发言人')}
							{poll_mode === 2 && t('带音频')}
						</CheckBox>
					</Wrap>
				)}
				<Modal
					open={isSavePlanOpen}
					title={t('保存预案')}
					width={400}
					height={300}
					okText={t('保存')}
					onOk={addPlan}
					onCancel={() => {
						update({ isSavePlanOpen: false })
					}}
					cancelText={t('取消')}
				>
					<StyledPlanModal>
						<div className="label">{t('预案名称')}</div>
						<Input
							width={250}
							placeholder={t('请输入预案名称')}
							focusMsg={t('预案名称最多可输入16个字符')}
							innerRef={inputRef}
							maxLength={16}
							rule={{
								required: {
									showIcon: false,
									msg: t('预案名称不能为空'),
								},
								regular: getCheckPreNameRule(SWITCH.characterLimit),
							}}
							value={name}
							onChange={(e, v) => update({ name: v })}
						/>
					</StyledPlanModal>
				</Modal>
			</RightWrap>
		</PollContext.Provider>
	)
}
export default Poll
